package com.example.blue;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.blue.ui.DynamicWaveFormView;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

public class TuoCorActivity extends AppCompatActivity implements DataProcessorManager.DataUpdateListener{
    private static final String TAG = "TuoCorActivity";
    private Button startButton;
    private String deviceId;
    private BluetoothService bluetoothService;
    private boolean isBound = false;
    private Handler handler = new Handler(Looper.getMainLooper());
    private Boolean saveFlag=false;
    private String bleRawData;
    private Integer saveCorrectNum=0;
    private static final Integer saveCorrectNumSum=1000;
    private String saveTuoArray;
    private String saveRawArray;
    private String rawoutAbsFilepath;
    private String accBiasAbsFilepath;
    private String rawDataAbsFilepath;
    private DynamicWaveFormView waveformViewX1;
    private DynamicWaveFormView waveformViewY1;
    private DynamicWaveFormView waveformViewZ1;
    private DynamicWaveFormView waveformViewX2;
    private DynamicWaveFormView waveformViewY2;
    private DynamicWaveFormView waveformViewZ2;
    private int dataCounterX1= 0;
    private int dataCounterY1= 0;
    private int dataCounterZ1= 0;
    private int dataCounterX2= 0;
    private int dataCounterY2= 0;
    private int dataCounterZ2= 0;
    private Thread workerThreadx1;
    private Thread workerThready1;
    private Thread workerThreadz1;
    private Thread workerThreadx2;
    private Thread workerThready2;
    private Thread workerThreadz2;
    private Boolean runningx1=false;
    private Boolean runningy1=false;
    private Boolean runningz1=false;
    private Boolean runningx2=false;
    private Boolean runningy2=false;
    private Boolean runningz2=false;
    private Spinner spinner;
    private Integer selectedSensorNum=0;
    private DataProcessorManager processorManager;
    private final ConcurrentLinkedQueue<Float> accxDataQueue = new ConcurrentLinkedQueue<>();
    private final ConcurrentLinkedQueue<Float> accyDataQueue = new ConcurrentLinkedQueue<>();
    private final ConcurrentLinkedQueue<Float> acczDataQueue = new ConcurrentLinkedQueue<>();
    private final ConcurrentLinkedQueue<Float> gryxDataQueue = new ConcurrentLinkedQueue<>();
    private final ConcurrentLinkedQueue<Float> gryyDataQueue = new ConcurrentLinkedQueue<>();
    private final ConcurrentLinkedQueue<Float> gryzDataQueue = new ConcurrentLinkedQueue<>();
    private ConcurrentLinkedQueue<byte[]> dataQueue = new ConcurrentLinkedQueue<>();

    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bluetoothService = binder.getService();
            isBound = true;
            dataQueue  = bluetoothService.getDataQueue();
//            if(dataQueue.isEmpty()){
//                new AlertDialog.Builder(TuoCorActivity.this)
//                        .setTitle("提示")
//                        .setMessage("未收到数据，请重试")
//                        .setPositiveButton("确定", (dialog, which) -> {
//                            finish();
//                        })
//                        .show();
//            }else {
                processorManager = DataProcessorManager.getInstance(dataQueue);
                processorManager.startProcessing();
//            }
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tuo_cor);
        // 开启返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(null);
        getSupportActionBar().setTitle("陀螺仪校准");

        SharedPreferences sp = getSharedPreferences("my_cache", Context.MODE_PRIVATE);
        deviceId = sp.getString("deviceId", "");
        System.out.println(deviceId);
        if (deviceId == "" || deviceId.isEmpty()) {
            Toast.makeText(TuoCorActivity.this,"未获取到蓝牙MAC地址，请重新连接",Toast.LENGTH_SHORT).show();
        }

        spinner=findViewById(R.id.modeSpinner);
        String[] options = {"传感器1", "传感器2", "传感器3", "传感器4", "传感器5", "传感器6"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_item,
                options
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
// 监听选择
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selected = options[position];
                if(position!=selectedSensorNum){
                    waveformViewX1.clearDataPoints();
                    waveformViewY1.clearDataPoints();
                    waveformViewZ1.clearDataPoints();
                    waveformViewX2.clearDataPoints();
                    waveformViewY2.clearDataPoints();
                    waveformViewZ2.clearDataPoints();
                }
                selectedSensorNum=position;
                //Toast.makeText(TuoCorActivity.this, "选择了: " + selectedSensorNum, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        waveformViewX1 = findViewById(R.id.waveformView1);
        waveformViewY1 = findViewById(R.id.waveformView2);
        waveformViewZ1 = findViewById(R.id.waveformView3);
        waveformViewX1.setYtitle("X轴加速度(m/s²)");
        waveformViewX1.setYRange(-20,20);
        waveformViewY1.setYtitle("Y轴加速度(m/s²)");
        waveformViewY1.setYRange(-20,20);
        waveformViewZ1.setYtitle("Z轴加速度(m/s²)");
        waveformViewZ1.setYRange(-20,20);

        waveformViewX2 = findViewById(R.id.waveformView4);
        waveformViewY2 = findViewById(R.id.waveformView5);
        waveformViewZ2 = findViewById(R.id.waveformView6);
        waveformViewX2.setYtitle("X轴角速度(deg/s)");
        waveformViewX2.setYRange(-500,500);
        waveformViewY2.setYtitle("Y轴角速度(deg/s)");
        waveformViewY2.setYRange(-500,500);
        waveformViewZ2.setYtitle("Z轴角速度(deg/s)");
        waveformViewZ2.setYRange(-500,500);


        startButton = findViewById(R.id.tuoCorrectBtn);
        startButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveFlag=true;
                Toast.makeText(TuoCorActivity.this, "开始校准", Toast.LENGTH_SHORT).show();
                String mac=deviceId.replace(":", "");
                System.out.println("tuocor----mac:"+mac);
                processorManager.setDeviceMac(mac);
                processorManager.setDataUpdateListener(TuoCorActivity.this);
//                processorManager.startProcessing();
                processorManager.setProcessingFunction(ProcessingFunction.AccGyroBias);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(this, BluetoothService.class);
        intent.putExtra("DEVICE_ADDRESS", deviceId); // 如果需要
        bindService(intent, connection, Context.BIND_AUTO_CREATE);

    }
    @Override
    public void onDataProcessed(ProcessedData data) {
        String processedValue = data.getValue();
        //  dataTextView.setText("收到数据: " + processedValue);
        String flag = data.getFlag();
        System.out.println("acccor-Flag:"+flag);
        System.out.println("acccor-Hex: " + processedValue);
        if(flag.equals("rawout")){
            String[] dataArr = processedValue.split(" ");   // 按逗号分割
            //  System.out.println("dataArr: " + dataArr);
            switch(selectedSensorNum){
                case 0:
                    String da1 = dataArr[0].length()>10?dataArr[0].substring(0,8):dataArr[0];
                    String da2 = dataArr[1].length()>10?dataArr[1].substring(0,8):dataArr[1];
                    String da3 = dataArr[2].length()>10?dataArr[2].substring(0,8):dataArr[2];
                    String da4 = dataArr[3].length()>10?dataArr[3].substring(0,8):dataArr[3];
                    String da5 = dataArr[4].length()>10?dataArr[4].substring(0,8):dataArr[4];
                    String da6 = dataArr[5].length()>10?dataArr[5].substring(0,8):dataArr[5];
//                    accxDataQueue.add(Float.parseFloat(da1));
//                    waveformViewY1.addDataPoint(Float.parseFloat(da2));
//                    waveformViewZ1.addDataPoint(Float.parseFloat(da3));
//                    waveformViewX2.addDataPoint((Float.parseFloat(da4)/3.1415926f)*180);
//                    waveformViewY2.addDataPoint((Float.parseFloat(da5)/3.1415926f)*180);
//                    waveformViewZ2.addDataPoint((Float.parseFloat(da6)/3.1415926f)*180);
                    waveformViewX1.addDataPoint(Float.parseFloat(da1));
                    waveformViewY1.addDataPoint(Float.parseFloat(da2));
                    waveformViewZ1.addDataPoint(Float.parseFloat(da3));
                    waveformViewX2.addDataPoint((Float.parseFloat(da4)/3.1415926f)*180);
                    waveformViewY2.addDataPoint((Float.parseFloat(da5)/3.1415926f)*180);
                    waveformViewZ2.addDataPoint((Float.parseFloat(da6)/3.1415926f)*180);
                    break;
                case 1:
                    String db1 = dataArr[9].length()>10?dataArr[9].substring(0,8):dataArr[9];
                    String db2 = dataArr[10].length()>10?dataArr[10].substring(0,8):dataArr[10];
                    String db3 = dataArr[11].length()>10?dataArr[11].substring(0,8):dataArr[11];
                    String db4 = dataArr[12].length()>10?dataArr[12].substring(0,8):dataArr[12];
                    String db5 = dataArr[13].length()>10?dataArr[13].substring(0,8):dataArr[14];
                    String db6 = dataArr[14].length()>10?dataArr[14].substring(0,8):dataArr[14];
                    waveformViewX1.addDataPoint(Float.parseFloat(db1));
                    waveformViewY1.addDataPoint(Float.parseFloat(db2));
                    waveformViewZ1.addDataPoint(Float.parseFloat(db3));
                    waveformViewX2.addDataPoint((Float.parseFloat(db4)/3.1415926f)*180);
                    waveformViewY2.addDataPoint((Float.parseFloat(db5)/3.1415926f)*180);
                    waveformViewZ2.addDataPoint((Float.parseFloat(db6)/3.1415926f)*180);
                    break;
                case 2:
                    String dc1 = dataArr[18].length()>10?dataArr[18].substring(0,8):dataArr[18];
                    String dc2 = dataArr[19].length()>10?dataArr[19].substring(0,8):dataArr[19];
                    String dc3 = dataArr[20].length()>10?dataArr[20].substring(0,8):dataArr[20];
                    String dc4 = dataArr[21].length()>10?dataArr[21].substring(0,8):dataArr[21];
                    String dc5 = dataArr[22].length()>10?dataArr[22].substring(0,8):dataArr[22];
                    String dc6 = dataArr[23].length()>10?dataArr[23].substring(0,8):dataArr[23];
                    waveformViewX1.addDataPoint(Float.parseFloat(dc1));
                    waveformViewY1.addDataPoint(Float.parseFloat(dc2));
                    waveformViewZ1.addDataPoint(Float.parseFloat(dc3));
                    waveformViewX2.addDataPoint((Float.parseFloat(dc4)/3.1415926f)*180);
                    waveformViewY2.addDataPoint((Float.parseFloat(dc5)/3.1415926f)*180);
                    waveformViewZ2.addDataPoint((Float.parseFloat(dc6)/3.1415926f)*180);
                    break;
                case 3:
                    String dd1 = dataArr[27].length()>10?dataArr[27].substring(0,8):dataArr[27];
                    String dd2 = dataArr[28].length()>10?dataArr[28].substring(0,8):dataArr[28];
                    String dd3 = dataArr[29].length()>10?dataArr[29].substring(0,8):dataArr[29];
                    String dd4 = dataArr[30].length()>10?dataArr[30].substring(0,8):dataArr[30];
                    String dd5 = dataArr[31].length()>10?dataArr[31].substring(0,8):dataArr[31];
                    String dd6 = dataArr[32].length()>10?dataArr[32].substring(0,8):dataArr[32];
                     waveformViewX1.addDataPoint(Float.parseFloat(dd1));
                    waveformViewY1.addDataPoint(Float.parseFloat(dd2));
                    waveformViewZ1.addDataPoint(Float.parseFloat(dd3));
                    waveformViewX2.addDataPoint((Float.parseFloat(dd4)/3.1415926f)*180);
                    waveformViewY2.addDataPoint((Float.parseFloat(dd5)/3.1415926f)*180);
                    waveformViewZ2.addDataPoint((Float.parseFloat(dd6)/3.1415926f)*180);
                    break;
                case 4:
                    String de1 = dataArr[36].length()>10?dataArr[36].substring(0,8):dataArr[36];
                    String de2 = dataArr[37].length()>10?dataArr[37].substring(0,8):dataArr[37];
                    String de3 = dataArr[38].length()>10?dataArr[38].substring(0,8):dataArr[38];
                    String de4 = dataArr[39].length()>10?dataArr[39].substring(0,8):dataArr[39];
                    String de5 = dataArr[40].length()>10?dataArr[40].substring(0,8):dataArr[40];
                    String de6 = dataArr[41].length()>10?dataArr[41].substring(0,8):dataArr[41];
                     waveformViewX1.addDataPoint(Float.parseFloat(de1));
                    waveformViewY1.addDataPoint(Float.parseFloat(de2));
                    waveformViewZ1.addDataPoint(Float.parseFloat(de3));
                    waveformViewX2.addDataPoint((Float.parseFloat(de4)/3.1415926f)*180);
                    waveformViewY2.addDataPoint((Float.parseFloat(de5)/3.1415926f)*180);
                    waveformViewZ2.addDataPoint((Float.parseFloat(de6)/3.1415926f)*180);
                    break;
                case 5:
                    String df1 = dataArr[45].length()>10?dataArr[45].substring(0,8):dataArr[45];
                    String df2 = dataArr[46].length()>10?dataArr[46].substring(0,8):dataArr[46];
                    String df3 = dataArr[47].length()>10?dataArr[47].substring(0,8):dataArr[47];
                    String df4 = dataArr[48].length()>10?dataArr[48].substring(0,8):dataArr[48];
                    String df5 = dataArr[49].length()>10?dataArr[49].substring(0,8):dataArr[49];
                    String df6 = dataArr[50].length()>10?dataArr[50].substring(0,8):dataArr[50];
                     waveformViewX1.addDataPoint(Float.parseFloat(df1));
                    waveformViewY1.addDataPoint(Float.parseFloat(df2));
                    waveformViewZ1.addDataPoint(Float.parseFloat(df3));
                    waveformViewX2.addDataPoint((Float.parseFloat(df4)/3.1415926f)*180);
                    waveformViewY2.addDataPoint((Float.parseFloat(df5)/3.1415926f)*180);
                    waveformViewZ2.addDataPoint((Float.parseFloat(df6)/3.1415926f)*180);
                    break;
            }
//            startThreadx1();
//            startThready1();
//            startThreadz1();
//            startThreadx2();
//            startThready2();
//            startThreadz2();
        }
        if(flag.equals("accgyrobias")){
           String[] accres = processedValue.split("\n");
            System.out.println("acccor"+accres[0]+" "+accres[1]+" "+accres[2]);
            //停止画图线程
            stopThreads();
            //跳转到结果页面
            Intent intent = new Intent(TuoCorActivity.this, TuoResActivity.class);
            intent.putExtra("accResult",processedValue);
            startActivity(intent);

        }
    }
    /** 启动线程（只允许一个） */
    private void startThreadx1() {
        if (workerThreadx1 != null && workerThreadx1.isAlive()) {
            Log.d("Waveform", "线程已在运行，不重复创建");
            return;
        }

        runningx1 = true;
        workerThreadx1 = new Thread(() -> {
            Log.d("Waveform", "线程启动");
            while (runningx1) {
                runOnUiThread(() -> {
                    if(!accxDataQueue.isEmpty()) {
                        waveformViewX1.addDataPoint(accxDataQueue.poll());
                    }
                });
                try {
                    Thread.sleep(10); // 20ms 一次
                } catch (InterruptedException e) {
                    break;
                }
            }
            Log.d("Waveform", "线程退出");
        });
        workerThreadx1.start();
    }
    /** 启动线程（只允许一个） */
    private void startThready1() {
        if (workerThready1 != null && workerThready1.isAlive()) {
            Log.d("Waveform", "线程已在运行，不重复创建");
            return;
        }
        runningy1 = true;
        workerThready1 = new Thread(() -> {
            Log.d("Waveform", "线程启动");
            while (runningy1) {
                runOnUiThread(() -> {
                    if(!accyDataQueue.isEmpty()) {
                        waveformViewY1.addDataPoint(accyDataQueue.poll());
                    }
                });
                try {
                    Thread.sleep(10); // 20ms 一次
                } catch (InterruptedException e) {
                    break;
                }
            }
            Log.d("Waveform", "线程退出");
        });
        workerThready1.start();
    }
    /** 启动线程（只允许一个） */
    private void startThreadz1() {
        if (workerThreadz1 != null && workerThreadz1.isAlive()) {
            Log.d("Waveform", "线程已在运行，不重复创建");
            return;
        }

        runningz1 = true;
        workerThreadz1 = new Thread(() -> {
            Log.d("Waveform", "线程启动");
            while (runningz1) {
                runOnUiThread(() -> {
                    if(!acczDataQueue.isEmpty()) {
                        waveformViewZ1.addDataPoint(acczDataQueue.poll());
                    }
                });


                try {
                    Thread.sleep(10); // 20ms 一次
                } catch (InterruptedException e) {
                    break;
                }
            }
            Log.d("Waveform", "线程退出");
        });
        workerThreadz1.start();
    }
    /** 启动线程（只允许一个） */
    private void startThreadx2() {
        if (workerThreadx2 != null && workerThreadx2.isAlive()) {
            Log.d("Waveform", "线程已在运行，不重复创建");
            return;
        }

        runningx2 = true;
        workerThreadx2 = new Thread(() -> {
            Log.d("Waveform", "线程启动");
            while (runningx2) {
                runOnUiThread(() -> {
                    if(!gryxDataQueue.isEmpty()) {
                        waveformViewX2.addDataPoint(gryxDataQueue.poll());
                    }
                });


                try {
                    Thread.sleep(10); // 20ms 一次
                } catch (InterruptedException e) {
                    break;
                }
            }
            Log.d("Waveform", "线程退出");
        });
        workerThreadx2.start();
    }
    /** 启动线程（只允许一个） */
    private void startThready2() {
        if (workerThready2 != null && workerThready2.isAlive()) {
            Log.d("Waveform", "线程已在运行，不重复创建");
            return;
        }

        runningy2 = true;
        workerThready2 = new Thread(() -> {
            Log.d("Waveform", "线程启动");
            while (runningy2) {
                runOnUiThread(() -> {
                    if(!gryyDataQueue.isEmpty()) {
                        waveformViewY2.addDataPoint(gryyDataQueue.poll());
                    }
                });


                try {
                    Thread.sleep(10); // 20ms 一次
                } catch (InterruptedException e) {
                    break;
                }
            }
            Log.d("Waveform", "线程退出");
        });
        workerThready2.start();
    }
    /** 启动线程（只允许一个） */
    private void startThreadz2() {
        if (workerThreadz2 != null && workerThreadz2.isAlive()) {
            Log.d("Waveform", "线程已在运行，不重复创建");
            return;
        }

        runningz2 = true;
        workerThreadz2 = new Thread(() -> {
            Log.d("Waveform", "线程启动");
            while (runningz2) {
                runOnUiThread(() -> {
                    if(!gryzDataQueue.isEmpty()) {
                        waveformViewZ2.addDataPoint(gryzDataQueue.poll());
                    }
                });


                try {
                    Thread.sleep(10); // 20ms 一次
                } catch (InterruptedException e) {
                    break;
                }
            }
            Log.d("Waveform", "线程退出");
        });
        workerThreadz2.start();
    }

    /** 停止线程 */
    private void stopThreads() {
        runningx1 = false;
        runningy1 = false;
        runningz1 = false;
        runningx2 = false;
        runningy2 = false;
        runningz2 = false;
        if (workerThreadx1 != null) {
            workerThreadx1.interrupt();
            workerThreadx1 = null;
        }
        if (workerThready1 != null) {
            workerThready1.interrupt();
            workerThready1 = null;
        }
        if (workerThreadz1 != null) {
            workerThreadz1.interrupt();
            workerThreadz1 = null;
        }
        if (workerThreadx2 != null) {
            workerThreadx2.interrupt();
            workerThreadx2 = null;
        }
        if (workerThready2 != null) {
            workerThready2.interrupt();
            workerThready2 = null;
        }
        if (workerThreadz2 != null) {
            workerThreadz2.interrupt();
            workerThreadz2 = null;
        }
        //清空画图数据
        accxDataQueue.clear();
        accyDataQueue.clear();
        acczDataQueue.clear();
        gryxDataQueue.clear();
        gryyDataQueue.clear();
        gryzDataQueue.clear();
    }

//    private void getRawoutPlugin(String value){
//        if(saveFlag==true){
//            if(saveCorrectNum<saveCorrectNumSum){
//                String resultRawout  = "callPlugin()";//todo
//                saveTuoArray = saveTuoArray + saveCorrectNum+" "+ resultRawout+"\n";
//                saveRawArray = saveRawArray+ saveCorrectNum+" "+value+"\n";
//                saveCorrectNum+=1;
//            }
//            if(saveCorrectNum==saveCorrectNumSum){
//                String fileName = "acc-rawout-data.txt";
//                saveRawoutFile(fileName,saveTuoArray);
//                String fileName2 = "acc-rawdata.txt";
//                saveRawdataFile(fileName2,saveRawArray);
//                saveFlag=false;
//            }
//        }
//
//    }
//    public boolean saveRawoutFile(String fileName, String content) {
//        // 检查外部存储是否可用
//        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            Log.e("FileSave", "外部存储不可用");
//            return false;
//        }
//
//        File file = new File(Environment.getExternalStoragePublicDirectory(
//                Environment.DIRECTORY_DOCUMENTS), fileName);
//
//        try {
//            // 确保目录存在
//            File parent = file.getParentFile();
//            if (!parent.exists() && !parent.mkdirs()) {
//                Log.e("FileSave", "创建目录失败");
//                return false;
//            }
//
//            FileWriter writer = new FileWriter(file);
//            writer.write(content);
//            writer.close();
//
//            Log.d("FileSave", "文件保存成功: " + file.getAbsolutePath());
//            rawoutAbsFilepath=file.getAbsolutePath();
//            getAccBias();
//            return true;
//        } catch (IOException e) {
//            Log.e("FileSave", "保存文件时出错: " + e.getMessage());
//            e.printStackTrace();
//            return false;
//        }
//    }
//    public boolean saveRawdataFile(String fileName, String content) {
//        // 检查外部存储是否可用
//        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            Log.e("FileSave", "外部存储不可用");
//            return false;
//        }
//
//        File file = new File(Environment.getExternalStoragePublicDirectory(
//                Environment.DIRECTORY_DOCUMENTS), fileName);
//
//        try {
//            // 确保目录存在
//            File parent = file.getParentFile();
//            if (!parent.exists() && !parent.mkdirs()) {
//                Log.e("FileSave", "创建目录失败");
//                return false;
//            }
//
//            FileWriter writer = new FileWriter(file);
//            writer.write(content);
//            writer.close();
//
//            Log.d("FileSave", "文件保存成功: " + file.getAbsolutePath());
//            rawDataAbsFilepath=file.getAbsolutePath();
//            return true;
//        } catch (IOException e) {
//            Log.e("FileSave", "保存文件时出错: " + e.getMessage());
//            e.printStackTrace();
//            return false;
//        }
//    }
//    private void getAccBias(){
//        //调用插件获取accBias
//        //todo
//        String resultMagbias = "callPlugin2(rawoutAbsFilepath)";
//        String filename = "accBias.txt";
//        saveAccBiasFile(filename,resultMagbias);
//    }
//    public boolean saveAccBiasFile(String fileName, String content) {
//        // 检查外部存储是否可用
//        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            Log.e("FileSave", "外部存储不可用");
//            return false;
//        }
//
//        File file = new File(Environment.getExternalStoragePublicDirectory(
//                Environment.DIRECTORY_DOCUMENTS), fileName);
//
//        try {
//            // 确保目录存在
//            File parent = file.getParentFile();
//            if (!parent.exists() && !parent.mkdirs()) {
//                Log.e("FileSave", "创建目录失败");
//                return false;
//            }
//
//            FileWriter writer = new FileWriter(file);
//            writer.write(content);
//            writer.close();
//
//            Log.d("FileSave", "文件保存成功: " + file.getAbsolutePath());
//            accBiasAbsFilepath=file.getAbsolutePath();
//            SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
//            SharedPreferences.Editor editor = sp.edit();
//            editor.putString("accBiasAbsFilepath", accBiasAbsFilepath);
//            editor.apply();
//
//            Toast.makeText(TuoCorActivity.this,"校准成功",Toast.LENGTH_SHORT).show();
//            Intent accInt = new Intent(TuoCorActivity.this, TuoResActivity.class);
//            accInt.putExtra("deviceId",deviceId);
//            accInt.putExtra("accResult",content);
//            startActivity(accInt);
//            return true;
//        } catch (IOException e) {
//            Log.e("FileSave", "保存文件时出错: " + e.getMessage());
//            e.printStackTrace();
//            return false;
//        }
//    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 结束当前Activity，返回上一个
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopThreads();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopThreads();
    }
}